<template>
  <div class="h-[calc(100%-60px)]">
    <div class="flex h-[100%]">
      <div class="overflow-auto mt-[8px]">
        <div class="pl-[8px] pb-[8px]">
          <BaseInfo
            ref="baseRef"
            :options="optionsData2"
            :data="detailData"
            id="基础信息"
          />
          <AddressInfo
            ref="addressRef"
            :data="detailData"
            id="物流商地址信息"
          />
          <FinancialInfo
            ref="financialRef"
            :options="optionsDataAll"
            :data="detailData"
            id="财务信息"
          />
          <!-- {{fileList}} -->
          <FileInfo ref="fileRef" id="文件信息" v-model="contract_files_list" />
        </div>
      </div>
      <div>
        <steps :list="sideNavigationData"></steps>
      </div>
    </div>
    <div
      class="flex items-center justify-center bg-[var(--base-color)] py-[10px] shadow-[0_-3px_6px_0_rgba(51,102,241,0.1)] relative z-10 ml-[8px]"
    >
      <el-button size="large" @click="handleCancel" :disabled="loading">
        取消
      </el-button>
      <el-button
        size="large"
        type="primary"
        @click="handleSave"
        :loading="loading"
      >
        保存
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { strHump } from "@/utils/index";
import BaseInfo from "./BaseInfo/index.vue";
import AddressInfo from "./AddressInfo/index.vue";
import FinancialInfo from "./FinancialInfo/index.vue";
import FileInfo from "./FileInfo/index.vue";
import { scrollTarget } from "@/hooks/scrollTop.js";
import { overallOptions } from "@/api/public.js";
import { useEnumSelect } from "@/hooks/useEnumSelect.js";
import action from "@/utils/action.js";
import {
  logisticsCreate,
  logisticsDetail,
  updateLogistics,
  logisticsBpConfig,
} from "../api/index";
import steps from "@/components/steps/index.vue";
import { computed } from "vue";
const router = useRouter();

const id = ref();
const detailData = ref({ id: "" });
const loading = ref(false);
const baseRef = ref();
const addressRef = ref();
const financialRef = ref();
const fileRef = ref();
const contract_files_list = ref([]);
const sideNavigationData = ref([
  { label: "基础信息" },
  { label: "物流商地址信息" },
  { label: "财务信息" },
  { label: "文件信息" },
]);
const optionsData = ref([]);
// const data = reactive({
//   scrollNode: "",
//   scrollNodeY: "",
//   parentNode: "",
//   sideActive: 1,
//   anchorsList: [],
//   countryOptions: [],
// });
// const {
//   scrollNode,
//   scrollNodeY,
//   parentNode,
//   sideActive,
//   anchorsList,
//   countryOptions,
// } = toRefs(data);
const { options: optionsData2 } = useEnumSelect({
  params: ["cls_invoice_tag"],
});
onMounted(() => {
  getOptions();
  const { id: idQuery } = router.currentRoute.value.query || {};

  if (idQuery) {
    id.value = idQuery;
    nextTick(() => getDetail());
  }
});

const getDetail = async () => {
  try {
    loading.value = true;
    const { data } = await logisticsDetail({ id: id.value });
    const { contract_files } = data;
    if (contract_files?.length) {
      let file_group = [];
      for (let i = 0; i < contract_files.length; i++) {
        file_group.push({
          name: contract_files[i].source_name,
          url: contract_files[i].oss_path,
          source_name: contract_files[i].filename,
          response: {
            ...contract_files[i],
          },
        });
      }
      data.contract_files = file_group;
    } else {
      data.contract_files = [];
    }
    detailData.value = data;
    contract_files_list.value = data?.contract_files || [];
  } catch (e) {
    console.warn(e);
  } finally {
    loading.value = false;
  }
};

const getOptions = async () => {
  try {
    const params = "logistics.logistics";
    const { data } = await overallOptions({
      params,
    });
    const _data = data?.[strHump(params)];
    if (_data) {
      optionsData.value = _data;
    }
  } catch (e) {
    console.error(e);
  }
};

const optionsData1 = ref({});
const logisticsBpConfigList = async () => {
  const { data } = await logisticsBpConfig();
  optionsData1.value.bp_config = data;
};
logisticsBpConfigList();
const optionsDataAll = computed(() => {
  return {
    ...optionsData1.value,
    ...optionsData.value,
  };
});
const handleCancel = () => {
  action.setGlobalState({
    changeMicoTabsPath: {
      type: "closeActiveTab",
    },
  });
};

const isEdit = computed(() => !!detailData.value?.id);

const handleSave = async () => {
  try {
    loading.value = true;
    const baseInfo = await baseRef.value.form.submit();
    const addressInfo = addressRef.value.getTableData();
    const { finance_details, ...reset } =
      await financialRef.value.getTableData();
    console.warn(finance_details, reset);

    const _api = {
      edit: updateLogistics,
      add: logisticsCreate,
    };
    let fileList = contract_files_list.value?.map((item) => item.response)||[];
    const res = await _api[isEdit.value ? "edit" : "add"]({
      id: detailData.value?.id || undefined,
      ...baseInfo,
      address_details: addressInfo,
      finance_details: finance_details,
      ...reset,
      contract_files: fileList,
    });
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return;
    }
    ElMessage.success("添加成功");
    handleCancel();
  } catch (e) {
    if (e?.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};
</script>
